﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using DAL;
using Newtonsoft.Json;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using System.IO;
using NPOI.HSSF.Util;
using Facade.Excel;

namespace PeisongWeb.admin
{
    public partial class buyerFixedPricePeriodList :adminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (hasPermission("CJ", 1))
                {
                    rptBind();
                }
                else
                {
                    Library.Script.ClientMsgUrl("没有权限！", "index.aspx");
                    return;
                }

            }
        }
        #region Part1      显示采购商固定价格列表经及详情
        void rptBind()
        {
            StringBuilder where = new StringBuilder();
            where.Append("1=1");
            if (txt_buyerName.Text.Trim() != "")
                where.AppendFormat(" and buyerName like '%{0}%'", txt_buyerName.Text.Trim());
            DataSet ds = logic.buyerFixedPricePeriod.select(where.ToString(), "inputDt desc", AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex);
            AspNetPager1.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            rpt_list.DataSource = ds.Tables[1];
            rpt_list.DataBind();
        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            rptBind();
        }

        protected void lbtn_Search_Click(object sender, EventArgs e)
        {
            rptBind();
        }

        protected void rpt_list_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "details")
            {
                int fpId = Convert.ToInt32(e.CommandArgument);
                getBuyerFixedPricePeriodItem(fpId);
                bfp_details.Show();
                hd_fpid.Value = fpId.ToString();
            }
        }

        private void getBuyerFixedPricePeriodItem(int fpId)
        {
            DataRow dr = logic.buyerFixedPricePeriod.select("fpid=" + fpId, "fpid", 1, 1).Tables[1].Rows[0];
            lbl_buyerName.Text = dr["buyerName"].ToString() + "　　　　配送周期：【" + dr["startTime"].ToString() + "至" + dr["endTime"].ToString()+"】";
            hd_buyerId.Value = dr["buyerId"].ToString();
            DataTable dt = logic.buyerFixedPricePeriodItem.select("fpid=" + fpId, "bpid desc", 1000, 1).Tables[1];
            rpt_bfpItems.DataSource = dt;
            rpt_bfpItems.DataBind();

            ViewState["CacheDetail"] = dt;
        }
        #endregion

        #region Part2  显示所有商品价格
        protected void lbn_Add_Click(object sender, EventArgs e)
        {
            categoryRootBind();
            categorySubBind();
            rpt_bfpItemBind();
            bfp_details.Show();
            win_product.Show();
        }
        void rpt_bfpItemBind()
        {
            StringBuilder where = new StringBuilder();
            where.Append("isSale=1");
            if (hd_fpid.Value!="")
                where.AppendFormat("and productId NOT IN (SELECT productId FROM dbo.buyerFixedPricePeriodItem WHERE fpid={0})", Convert.ToInt32(hd_fpid.Value));
            if (ddl_CategorySub.SelectedValue != "")
                where.AppendFormat("and categoryId={0}", ddl_CategorySub.SelectedValue);
            if (txt_ProductNo.Text.Trim() != "")
                where.AppendFormat(" and productNo like '%{0}%'", txt_ProductNo.Text.Trim());
            if (txt_ProductName.Text.Trim() != "")
                where.AppendFormat(" and [Name] like '%{0}%'", txt_ProductName.Text.Trim());
            DataSet ds = logic.sellerRange.snnightOrderOptimize(where.ToString(), "productId", AspNetPager2.PageSize, AspNetPager2.CurrentPageIndex);
            AspNetPager2.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            ViewState["seller"] = ds.Tables[2];
            rpt_Products.DataSource = ds.Tables[1];
            rpt_Products.DataBind();
        }
        protected void rpt_Products_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                DropDownList ddl = e.Item.FindControl("ddl") as DropDownList;
                DataRowView dv = e.Item.DataItem as DataRowView;

                DataTable dt = ViewState["seller"] as DataTable;
                DataView view = new DataView(dt);
                view.RowFilter = string.Format("productId={0}", dv["productId"]);
                view.Sort = "coi DESC";

                ddl.DataSource = view;
                ddl.DataBind();
            }
        }
        protected void lbn_search_Click(object sender, EventArgs e)
        {
            AspNetPager2.CurrentPageIndex = 1;
            rpt_bfpItemBind();
        }
        protected void AspNetPager2_PageChanged(object sender, EventArgs e)
        {
            rpt_bfpItemBind();
        }

        void categoryRootBind()
        {
            ddl_CategoryRoot.DataSource = logic.category.getByParent(0);
            ddl_CategoryRoot.DataBind();
            ddl_CategoryRoot.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));
        }

        void categorySubBind()
        {
            if (ddl_CategoryRoot.SelectedValue != "")
            {
                DataTable dt = logic.category.getByParent(Convert.ToInt32(ddl_CategoryRoot.SelectedValue));
                ddl_CategorySub.DataSource = dt;
                ddl_CategorySub.DataBind();
            }
            else
            {
                ddl_CategorySub.Items.Clear();
            }
        }

        protected void ddl_CategoryRoot_SelectedIndexChanged(object sender, EventArgs e)
        {
            categorySubBind();
            AspNetPager2.CurrentPageIndex = 1;
            rpt_bfpItemBind();
        }

        protected void ddl_CategorySub_SelectedIndexChanged(object sender, EventArgs e)
        {
            AspNetPager2.CurrentPageIndex = 1;
            rpt_bfpItemBind();
        }

        // 导出详细信息
        protected void link_Export_Detail_Click(object sender,EventArgs e)
        {
            DataTable dt = ViewState["CacheDetail"] as DataTable;
            if (dt.Rows.Count>0)
            {
                // 筛选表中部分列
                DataTable newTab=dt.DefaultView.ToTable(false, new string[] {"proName","sellerName","sellerPrice","price","inputDt","inputName"});
                newTab.Columns[0].ColumnName = "商品名称";
                newTab.Columns[1].ColumnName = "供应商名称";
                newTab.Columns[2].ColumnName = "供应价";
                newTab.Columns[3].ColumnName = "采购价";
                newTab.Columns[4].ColumnName = "创建日期";
                newTab.Columns[5].ColumnName = "创建人";
                string title = lbl_buyerName.Text;

                // 导出Excel
                ExportFacade exportInstance = new Facade.Excel.ExportFacade();
                Dictionary<int, FormatStyle> formatOptions = new Dictionary<int, FormatStyle>();
                formatOptions.Add(2, FormatStyle.ToFix2);
                formatOptions.Add(3, FormatStyle.ToFix2);

                exportInstance.ExportByWeb(newTab, title, title + ".xls", formatOptions, title);
            }
        }

        #endregion

        #region Part3  添加新增加商品价格
        protected void btn_Save_Click(object sender, EventArgs e)
        {
            // 日志记录
            log4net.ILog logger = log4net.LogManager.GetLogger("ApplicationFileAppender");//读取log4net的配置文件
            logger.Info("新增采购商固定价格商品信息:" + hd_proScope.Value);

            //// 采购固定价格商品细目
            List<BuyerFixedPricePeriodItemEntity> bfpItems = JsonConvert.DeserializeObject<List<BuyerFixedPricePeriodItemEntity>>(hd_proScope.Value);

            if (bfpItems.Count > 0)
            {
                int fpId = Convert.ToInt32(hd_fpid.Value);
                foreach (BuyerFixedPricePeriodItemEntity item in bfpItems)
                {
                    item.Fpid = fpId;
                    item.AdminId = logic.sysAdmin.AdminID;
                    logic.buyerFixedPricePeriodItem.insert(item);
                }
                Library.Script.ClientMsgUrl("固定价格保存成功!", "buyerFixedPricePeriodList.aspx");
            }
            else
            {
                Library.Script.ClientMsg("固定价格数据无效！");
                return;
            }
            hd_buyerId.Value = "";
            hd_fpid.Value = "";
            hd_proScope.Value = "";
        }
        #endregion
    }
}
